import React, { useState, useRef, useEffect } from 'react';
import AiChat from './AiChat';
import './SimpleFloatingBall.css';

const SimpleFloatingBall: React.FC = () => {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [dragStartTime, setDragStartTime] = useState(0);
  const [showChat, setShowChat] = useState(false);
  const ballRef = useRef<HTMLDivElement>(null);

  // 初始化位置（右下角）
  useEffect(() => {
    const updatePosition = () => {
      if (ballRef.current) {
        const rect = ballRef.current.getBoundingClientRect();
        setPosition({
          x: window.innerWidth - rect.width - 20,
          y: window.innerHeight - rect.height - 20
        });
      }
    };
    
    updatePosition();
    window.addEventListener('resize', updatePosition);
    return () => window.removeEventListener('resize', updatePosition);
  }, []);

  const handleMouseDown = (e: React.MouseEvent) => {
    setDragStartTime(Date.now());
    setIsDragging(true);
    
    if (ballRef.current) {
      const rect = ballRef.current.getBoundingClientRect();
      setDragOffset({
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      });
    }
  };

  const handleMouseMove = (e: MouseEvent) => {
    if (!isDragging) return;
    
    const newX = e.clientX - dragOffset.x;
    const newY = e.clientY - dragOffset.y;
    
    // 限制在视窗范围内
    const maxX = window.innerWidth - 72; // 悬浮球宽度
    const maxY = window.innerHeight - 72; // 悬浮球高度
    
    setPosition({
      x: Math.max(0, Math.min(newX, maxX)),
      y: Math.max(0, Math.min(newY, maxY))
    });
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  // 添加全局鼠标事件监听
  useEffect(() => {
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, dragOffset, dragStartTime]);

  const handleClick = (e: React.MouseEvent) => {
    const clickDuration = Date.now() - dragStartTime;
    
    // 如果点击时间很短（小于150ms）且没有拖拽，认为是点击
    if (clickDuration < 150 && !isDragging) {
      setShowChat(true);
    }
  };

  return (
    <>
      <div 
        ref={ballRef}
        className={`simple-floating-ball ${isDragging ? 'dragging' : ''}`}
        style={{
          left: `${position.x}px`,
          top: `${position.y}px`,
          position: 'fixed'
        }}
        onMouseDown={handleMouseDown}
        onClick={handleClick}
      >
        <div className="simple-floating-ball-icon">
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="10" stroke="#fff" strokeWidth="2"/>
            <path d="M8 12h8M12 8v8" stroke="#fff" strokeWidth="2" strokeLinecap="round"/>
            <circle cx="12" cy="12" r="3" fill="#fff"/>
          </svg>
        </div>
        <div className="simple-floating-ball-tooltip">
          {isDragging ? '拖拽中...' : '点击开始AI对话'}
        </div>
      </div>

      {/* AI聊天对话框 */}
      {showChat && (
        <div className="floating-ball-chat-overlay">
          <AiChat onClose={() => setShowChat(false)} />
        </div>
      )}
    </>
  );
};

export default SimpleFloatingBall;
